﻿using System;
using System.Globalization;

namespace EpiNEXT.Services.Validation.Functions
{
    public abstract class DateComponentBase : FunctionBase
    {
        public DateComponentBase()
            : base()
        {
        }

        protected DateTime? GetDate(object boxedParamDate, Record record)
        {
            DateTime? date = null;
            DataEntryInstrument form = record.Form;

            string dateString = boxedParamDate.ToString();

            if (Char.IsDigit(dateString[0]))
            {
                date = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
            }
            else
            {
                object fieldValue = record.GetFieldData(form.Fields[dateString]);
                if (fieldValue == null)
                {
                    return null;
                }
                else
                {
                    date = (DateTime)fieldValue;
                }
            }

            return date;
        }
    }
}
